package com.sheye.UserDaoImpl;

import com.sheye.User.User;
import com.sheye.Util.JdbcUtil;


import java.sql.*;

import static com.sheye.Util.JdbcUtil.closeAll;
import static com.sheye.Util.JdbcUtil.eccuteDML;
import static com.sheye.Util.JdbcUtil.getConnection;

/** 业务层
 * @author Sheye
 * @date 2019-04-19 18:48
 * PrepareStatement 防止 select * from t_user where uname = '"+uname+"'and pwd = '"+pwd+"' or 1=1
 * 直接可以登陆成功,ps还有预编译的功能，提高sql的效率
 * 听着好像是classnotfound只能用try 而sqlexception可以直接被抛出
 */
public class UserDaoImpl {

    public User getUserInfo(String uname, int pwd) throws ClassNotFoundException, SQLException {
        //声明U，如果不声明，到后面就没有返回值
            User u = null;
        //加载驱动类
//            Class.forName(driver);
        //连接数据库
//            Connection conn = DriverManager.getConnection(url,username,password);
//                Connection conn = getConnection();
//        getConnection();
        //创建Sql命令对象
            String sql = "select * from t_user where uname = ? and pwd = ?";
        //创建SQL命令
            PreparedStatement ps = getConnection().prepareStatement(sql);
        //给占位符赋值
            ps.setString(1,uname);
            ps.setInt(2,pwd);
        //执行sql语句(ps已经执行sql,excuteQuery()就不再写sql)
            ResultSet rs = ps.executeQuery();
            while (rs.next()){  //如果是一列就不要这个
                u = new User();
                //getString(uname);取当前行的uname字段
                u.setUid(rs.getInt("uid"));
                u.setUname(rs.getString("uname"));
                u.setPwd(rs.getInt("pwd"));
                return u;
            }
            //关闭资源
//            getConnection().close();
//            ps.close();
//            rs.close();
            closeAll(rs,ps,getConnection());
            return u;
    }

    //新增
    public int insUser() throws SQLException {
        String sql="insert into t_user values(?,?,?)";
        int i =eccuteDML(sql,3,"wangwu","000");
        return i;
    }

    public static void main(String[] args) throws SQLException {
        UserDaoImpl ud = new UserDaoImpl();
        int i =ud.insUser();
        if (i>0){
            System.out.println("注册成功");
        }else{
            System.out.println("您输入的格式有问题" +
                    "：");
        }
    }

}
